﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QRCode2.Models;
using System.Net;
using System.Drawing;
using System.Drawing.Imaging;

namespace QRCode2.Controllers
{
    public class AgentQRCodeController : Controller
    {
        public AgentQRCodeDBContext db = new AgentQRCodeDBContext();
        public UserDBContext dbUser = new UserDBContext();
        public CompanyDBContext dbCompany = new CompanyDBContext();
       
        //
        // GET: /AgentQRCode/

        public ActionResult Index()
        {
            return View(db.AgentQRCodes.ToList());
        }

        //
        // GET: /AgentQRCode/Details/5

        public ActionResult Details(int id = 0)
        {
            AgentQRCode agentqrcode = db.AgentQRCodes.Find(id);
            if (agentqrcode == null)
            {
                return HttpNotFound();
            }
            return View(agentqrcode);
        }

        //
        // GET: /AgentQRCode/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /AgentQRCode/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(AgentQRCode agentqrcode)
        {
            if (ModelState.IsValid)
            {
                db.AgentQRCodes.Add(agentqrcode);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(agentqrcode);
        }

        //
        // GET: /AgentQRCode/Edit/5

        public ActionResult Edit(int id = 0)
        {


            AgentQRCode agentqrcode = db.AgentQRCodes.Find(id);

            try
            {


                if (agentqrcode == null)
                {
                    if (User.Identity.Name != "admin")
                    {
                        var agentqrcodes = db.AgentQRCodes.Where(b => b.AgentUserName == User.Identity.Name).ToList();

                        if (agentqrcodes.Count == 1)
                            agentqrcode = agentqrcodes[0];

                    }
                }

                if (agentqrcode == null)
                {
                    return HttpNotFound();
                }

                string QRCodeLocation = "";
                string BusinessCardLocation = "";
                string FlyerLocation = "";

                if (agentqrcode.QRCode != null)
                {
                    QRCodeLocation = ("~/Images/Agent/QRCode/") + agentqrcode.QRCode.ToString();

                    BusinessCardLocation = ("~/Images/Agent/BusinessCard/") + agentqrcode.BusinessCard.ToString();

                    FlyerLocation = ("~/Images/Agent/Flyer/") + agentqrcode.Flyer.ToString();

                }

                if (QRCodeLocation == null)
                    ViewBag.QRCodeLocation = "";
                else
                    ViewBag.QRCodeLocation = QRCodeLocation;

                if (BusinessCardLocation == null)
                    ViewBag.BusinessCardLocation = "";
                else
                    ViewBag.BusinessCardLocation = BusinessCardLocation;

                if (FlyerLocation == null)
                    ViewBag.FlyerLocation = "";
                else
                    ViewBag.FlyerLocation = FlyerLocation;
            }

            catch
            {
                return RedirectToAction("Index", "Home", new { area = "" });
            }

            return View(agentqrcode);
        }

        //
        // POST: /AgentQRCode/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(AgentQRCode agentqrcode)
        {
            if (ModelState.IsValid)
            {

                string imageLocation = "";
                string QRCode = Request.Form["QRCode"];

                //Create QR Code if doesn't exists
                if (QRCode == "")
                {
                    Guid guid = Guid.NewGuid();

                    Company company = dbCompany.Companies.Find(1);

                    string googleChartUrl = "http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=" + company.Domain + "/User/Details/?agentqr=" + guid.ToString();

                    imageLocation = Server.MapPath("~/Images/Agent/QRCode/") + guid.ToString() + ".jpg";

                    WebClient webClient = new WebClient();
                    webClient.DownloadFile(googleChartUrl, imageLocation);

                    agentqrcode.Code = guid.ToString();
                    agentqrcode.QRCode = guid.ToString() + ".jpg";
                }
                else
                {
                    agentqrcode.Code = QRCode.Substring(0,QRCode.Length-4);
                    agentqrcode.QRCode = QRCode;
                    imageLocation = Server.MapPath("~/Images/Agent/QRCode/") + QRCode;
                }

                string bcLocation = Server.MapPath("~/Images/BusinessCard.png");

                var users = dbUser.Users.Where(b => b.UserName == User.Identity.Name).ToList();
                User user = users[0];

                Image BImg = Image.FromFile(bcLocation);

                //User
                string imageUserLocation = Server.MapPath("~/Images/User/") + user.Picture.ToString();
                Image UImg = Image.FromFile(imageUserLocation);

                //QRCode
                Bitmap original = (Bitmap)Image.FromFile(imageLocation);
                Bitmap resized = new Bitmap(original, new Size(90, 90));

                Graphics g = Graphics.FromImage(BImg);
                g.DrawImage(UImg, 10, 15);
                g.DrawImage(resized, 170, 0);

                //Write text

                string font = "Arial";

                g.DrawString(user.FirstName + " " + user.LastName, new Font(font, 12, FontStyle.Regular), new SolidBrush(Color.FromArgb(254, Color.Black)), new Point(4, 80));
                g.DrawString("Sales Representative", new Font(font, 8, FontStyle.Regular), new SolidBrush(Color.FromArgb(254, Color.Red)), new Point(5, 95));
                g.DrawString("Phone : " + user.PhoneNumber, new Font(font, 8, FontStyle.Regular), new SolidBrush(Color.FromArgb(254, Color.Black)), new Point(5, 105));
                g.DrawString("Email : " + user.Email, new Font(font, 8, FontStyle.Regular), new SolidBrush(Color.FromArgb(254, Color.Black)), new Point(5, 115));


                Guid guidBC = Guid.NewGuid();
                bcLocation = Server.MapPath("~/Images/Agent/BusinessCard/") + guidBC.ToString() + ".bmp";

                BImg.Save(bcLocation);

                agentqrcode.BusinessCard = guidBC.ToString() + ".bmp";

                //Create Flyer

                Guid guidFL = Guid.NewGuid();

                string flLocation = Server.MapPath("~/Images/Flyer.png");

                Image FLImg = Image.FromFile(flLocation);

                Graphics flagGraphicsFL = Graphics.FromImage(FLImg);

                flagGraphicsFL.DrawImage(UImg, 10, 655);
                flagGraphicsFL.DrawImage(resized, 480, 640);

                flagGraphicsFL.DrawString(user.FirstName + " " + user.LastName, new Font(font, 12, FontStyle.Regular), new SolidBrush(Color.FromArgb(254, Color.Black)), new Point(99, 650));
                flagGraphicsFL.DrawString("Sales Representative", new Font(font, 8, FontStyle.Regular), new SolidBrush(Color.FromArgb(254, Color.Red)), new Point(100, 670));
                flagGraphicsFL.DrawString("Phone : " + user.PhoneNumber, new Font(font, 8, FontStyle.Regular), new SolidBrush(Color.FromArgb(254, Color.Black)), new Point(100, 695));
                flagGraphicsFL.DrawString("Email : " + user.Email, new Font(font, 8, FontStyle.Regular), new SolidBrush(Color.FromArgb(254, Color.Black)), new Point(100, 705));


                flLocation = Server.MapPath("~/Images/Agent/Flyer/") + guidFL.ToString() + ".png";
                FLImg.Save(flLocation);

                agentqrcode.Flyer = guidFL.ToString() + ".png";


                //Save Data

                agentqrcode.Active = true;

                agentqrcode.AgentUserName = User.Identity.Name;

                db.Entry(agentqrcode).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", "Home", new { area = "" });
            }
            return View(agentqrcode);
        }

        //
        // GET: /AgentQRCode/Delete/5

        public ActionResult Delete(int id = 0)
        {
            AgentQRCode agentqrcode = db.AgentQRCodes.Find(id);
            if (agentqrcode == null)
            {
                return HttpNotFound();
            }
            return View(agentqrcode);
        }

        //
        // POST: /AgentQRCode/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            AgentQRCode agentqrcode = db.AgentQRCodes.Find(id);
            db.AgentQRCodes.Remove(agentqrcode);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}